package cn.satoken.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.satoken.common.TokenInfo;
import cn.satoken.entity.SysMenu;
import cn.satoken.entity.SysUser;
import cn.satoken.mapper.SysUserMapper;
import cn.satoken.service.SysMenuService;
import cn.satoken.service.impl.SysUserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import static cn.satoken.constant.StatusConstant.*;

/**
 * <h3>saToken</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-04-25 16:04:57
 */
@RestController()
@RequestMapping("/menu/")
@RequiredArgsConstructor
public class SysMenuController {
    private final SysMenuService sysMenuService;
    private final SysUserServiceImpl service;
    private final SysUserMapper sysUserMapper;

    /**
     * 查询所有菜单
     * @return
     */
    @RequestMapping("selectAll")
    public SaResult selectAll() {
        return sysMenuService.selectAll();
    }

    /**
     * 修改
     * @param sysMenu
     * @return
     */
    @PostMapping("/update")
    public SaResult update(@RequestBody SysMenu sysMenu) {
        Long loginId = Long.valueOf(StpUtil.getLoginId().toString());
        sysMenu.setUpdateBy(loginId);
        if (sysMenu.getId() != null) {
            return sysMenuService.updateById(sysMenu)? SaResult.ok(UPDATE_SUCCESS) : SaResult.error(UPDATE_ERRO);
        }else {
            sysMenu.setCreateBy(loginId);
            return sysMenuService.save(sysMenu)?SaResult.ok(SAVE_SUCCESS) : SaResult.error(SAVA_ERRO);
        }
    }

    /**
     * 查询权限
     * @param id
     * @return
     */
    @GetMapping("/tokenInfo/{id}")
    public SaResult tokenInfo(@PathVariable Long id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        if (sysUser == null) {
            return SaResult.error(SELECT_ID_DATA_ERRO);
        }
        TokenInfo tokenInfo =new TokenInfo(StpUtil.getTokenInfo()) ;
        service.getTokenInfo(tokenInfo,sysUser);
        return SaResult.data(tokenInfo.getMenus());
    }
}
